<template>
  <el-drawer
    :title="title"
    :visible.sync="dialogFormVisible"
    size="500px"
    @close="close"
  >
    <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="教室名称" prop="name">
        <el-input v-model.trim="formData.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="教室地址" prop="address">
        <el-input v-model.trim="formData.address" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script>
  import { createClassroom, updateClassroom } from '@/apis/classroom'

  export default {
    name: 'ClassroomEditor',
    data() {
      return {
        formData: {
          name: null,
          address: null,
        },
        rules: {
          name: [
            { required: true, trigger: 'change', message: '请输入教室名称' },
          ],
          address: [
            { required: true, trigger: 'change', message: '请输入地址' },
          ],
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    methods: {
      showEdit(row) {
        if (!row) {
          this.title = '添加'
        } else {
          this.title = '编辑'
          this.formData = Object.assign({}, row)
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.formData = this.$options.data().formData
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            let actionFn

            const { id, name, address } = this.formData
            if (id) {
              actionFn = updateClassroom
            } else {
              actionFn = createClassroom
            }
            await actionFn({
              id,
              name,
              address,
            })
            this.$baseMessage('操作成功', 'success')
            this.$emit('on-success')
            this.close()
          } else {
            return false
          }
        })
      },
    },
  }
</script>
